package cn.cellcom.agent.struts.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.scienjus.smartqq.client.SmartQQClient;
import com.scienjus.smartqq.model.Category;

import cn.cellcom.adapter.service.QqMessageCallback;
import cn.cellcom.agent.biz.TChannelBiz;
import cn.cellcom.agent.biz.TGroupBiz;
import cn.cellcom.agent.hql.TChannelHql;
import cn.cellcom.agent.pojo.TChannel;
import cn.cellcom.agent.pojo.TGroup;
import cn.cellcom.agent.pojo.TUser;
import cn.cellcom.agent.struts.form.TChannelForm;
import cn.cellcom.jar.biz.AbstractBiz;
import cn.cellcom.jar.env.Env;
import cn.cellcom.jar.logon.LogonSession;
import cn.cellcom.jar.pagination.AbstractPaginationBiz;
import cn.cellcom.jar.pagination.IPaginationBiz;
import cn.cellcom.jar.util.ABean;
import cn.cellcom.jar.util.BeanUtil;
import cn.cellcom.jar.util.LogUtil;
import cn.cellcom.jar.util.MyException;

public class TChannelDpAct extends DispatchAction {

	private IPaginationBiz pbiz;

	private TChannelBiz cbiz;

	private TGroupBiz gbiz;

	private Logger log = LoggerFactory.getLogger(this.getClass());

	/**
	 * 查询记录
	 * 
	 * @param mapping
	 * @param fm
	 * @param req
	 * @param rep
	 * @return
	 */
	public ActionForward list(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse rep) {
		form = (ActionForm) AbstractPaginationBiz.getPaginationActionForm(req, form);
		List list = null;
		try {
			req.setAttribute("typelist", BeanUtil.startWith("TChannel-type"));
			/*
			 * req.setAttribute("open1list", BeanUtil.startWith("TChannel-open1"));
			 * req.setAttribute("show1list", BeanUtil.startWith("TChannel-show1"));
			 */

			log.info("查询的语句：TChannelHql()");
			list = pbiz.pagination(mapping, form, req, new TChannelHql()).getDataResult();

			req.setAttribute(Env.DATA_NAME, list);
		} catch (MyException e) {
			return LogUtil.e(this.clazz, "操作出现错误", e, mapping, req);
		}
		// typelist是从context中读取的，这里无需有读取代码
		// 存在读取数据库的配置

		return mapping.findForward("list");
	}

	/**
	 * 准备记录添加
	 * 
	 * @param mapping
	 * @param fm
	 * @param req
	 * @param rep
	 * @return
	 */
	public ActionForward add(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse rep) {
		req.setAttribute("typelist", BeanUtil.startWith("TChannel-type"));
		/*
		 * req.setAttribute("open1list", BeanUtil.startWith("TChannel-open1"));
		 * req.setAttribute("show1list", BeanUtil.startWith("TChannel-show1"));
		 */
		return mapping.findForward("add");
	}

	/**
	 * 执行记录添加
	 * 
	 * @param mapping
	 * @param fm
	 * @param req
	 * @param rep
	 * @return
	 */
	public ActionForward doAdd(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse rep) {
		TChannelForm fm = (TChannelForm) form;
		Object obj = cbiz.add(req, fm, null);
		log.info("新增记录结果：" + obj);
		String message;
		if (obj == null || !(obj instanceof TChannel)) {
			req.setAttribute(Env.DATA_NAME, "操作失败，" + obj);
			return mapping.findForward("error");
		} else {
			message = "记录添加成功";
		}

		add(mapping, fm, req, rep);
		// req.setAttribute("success", fm);
		req.setAttribute(Env.DATA_NAME, message);
		return mapping.findForward("add");
	}

	/**
	 * 准备修改记录
	 * 
	 * @param mapping
	 * @param fm
	 * @param req
	 * @param rep
	 * @return
	 */
	public ActionForward modify(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse rep) {
		TChannelForm fm = (TChannelForm) form;
		try {
			java.lang.String key = fm.getId();
			TChannel rf = (TChannel) cbiz.getDao().myGet(TChannel.class, key);
			if (rf == null) {
				req.setAttribute(Env.DATA_NAME, "读取数据错误");
				return mapping.findForward("error");
			}
			req.setAttribute(Env.DATA_NAME, rf);

			/*
			 * req.setAttribute("open1list", BeanUtil.startWith("TChannel-open1"));
			 * req.setAttribute("show1list", BeanUtil.startWith("TChannel-show1"));
			 */
			req.setAttribute("typelist", BeanUtil.startWith("TChannel-type"));

			LogonSession ls = new LogonSession(req);
			TUser user = (TUser) ls.getLogonObject();
			// 已经被该渠道所路由的技能组
			List<TGroup> selectedRouterGroupList = cbiz.getRouteGroupsByNo(user.getPid(), fm.getId());
			// 所有的技能组
			List<TGroup> allGroupList = gbiz.getGroupList(user.getPid());
			// 把坐席标记为已经选择
			for (int i = 0; selectedRouterGroupList != null && i < selectedRouterGroupList.size(); i++) {
				TGroup one = selectedRouterGroupList.get(i);
				for (int j = 0; j < allGroupList.size(); j++) {
					TGroup two = allGroupList.get(j);
					if (one.getId().equals(two.getId())) {
						two.setTmp("xx");
					}
				}
			}

			List<ABean> beanList = BeanUtil.toABeanList(allGroupList, "id", "name,no", "tmp");
			req.setAttribute("grouplist", beanList);
		} catch (MyException e) {
			return LogUtil.e(this.clazz, "读取数据错误", e, mapping, req);
		}
		return mapping.findForward("modify");
	}

	/**
	 * 执行记录修改
	 * 
	 * @param mapping
	 * @param fm
	 * @param req
	 * @param rep
	 * @return
	 */
	public ActionForward doModify(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse rep) {
		TChannelForm fm = (TChannelForm) form;
		Object obj = cbiz.modify(req, fm, null);
		log.info("修改记录结果：" + obj);
		if (obj == null || !(obj instanceof TChannel)) {
			req.setAttribute(Env.DATA_NAME, "操作失败，" + obj);
			return mapping.findForward("error");
		}
		req.setAttribute(Env.DATA_NAME, "记录修改成功");
		return mapping.findForward("success");
	}

	/**
	 * 登陆QQ
	 */
	private static List<SmartQQClient> QQ_LIST = new ArrayList<SmartQQClient>();

	/**
	 * 获取正在登陆的QQ
	 * 
	 * @param user
	 * 
	 * @return
	 */
	public SmartQQClient getLoginQq(String serial, TUser user) {
		for (int i = 0; i < QQ_LIST.size(); i++) {
			SmartQQClient q = QQ_LIST.get(i);
			if (q.getSerial().equals(serial)) {
				return q;
			}
		}
		/*
		 * QQ和回调对象相互引用
		 */
		QqMessageCallback callback = new QqMessageCallback(cbiz, user.getOrg(), user.getPid());
		SmartQQClient qq = new SmartQQClient(callback, user.getPid(), serial);
		callback.setSmartQQClient(qq);
		QQ_LIST.add(qq);
		return qq;
	}

	public void removeLoginQq(String serial) {
		List<SmartQQClient> removing = new ArrayList<SmartQQClient>();
		for (int i = 0; i < QQ_LIST.size(); i++) {
			SmartQQClient q = QQ_LIST.get(i);
			if (q.getSerial().equals(serial) || q.getUserInfo() == null) {
				removing.add(q);
				try {
					q.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		for (int j = 0; j < removing.size(); j++) {
			QQ_LIST.remove(removing.get(j));
		}

	}

	/**
	 * QQ登陆
	 * 
	 * @param mapping
	 * @param form
	 * @param req
	 * @param rep
	 * @return
	 */
	public ActionForward qqLogin(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse rep) {
		LogonSession ls = new LogonSession(req);
		TUser user = (TUser) ls.getLogonObject();

		String serial = req.getParameter("serial");
		String action = req.getParameter("action");
		log.info("QQLogin: serial is [{}], and action is [{}]", serial, action);
		if ("list".equals(action)) {
			List<Map> stringList = new ArrayList<Map>();
			for (int i = 0; i < QQ_LIST.size(); i++) {
				SmartQQClient one = QQ_LIST.get(i);
				if (user.getPid().equals(one.getPid())) {
					Map e = new HashMap<>();
					e.put("serial", one.getSerial());
					e.put("number", one.getUserInfo().getAccount());
					stringList.add(e);
				}
			}
			Response.succ(rep, stringList);
			return null;
		}
		SmartQQClient qq = getLoginQq(serial, user);
		QqMessageCallback callback = (QqMessageCallback) qq.getCallback();
		if ("getCategory".equals(action)) {
			List<Category> categoryList = callback.getCategories();
			Response.succ(rep, categoryList);
			return null;
		} else if ("cancel".equals(action)) {
			removeLoginQq(serial);
		} else if ("result".equals(action)) {
			if (QqMessageCallback.RESULT.SUCCESS.equals(callback.getResult())) {
				if (callback.getUserInfo() == null) {
					System.out.println();
				}
				Response.succ(rep, callback.getResult().name() + callback.getUserInfo().getAccount());
			} else {
				Response.succ(rep, callback.getResult().name());
			}
		} else {
			if (QqMessageCallback.RESULT.WAITING.equals(callback.getResult())) {// 等待扫描
				Response.succ(rep, callback.getQrCode());
			}
		}

		return null;
	}

	public void setCbiz(AbstractBiz cbiz) {
		this.cbiz = (TChannelBiz) cbiz;
	}

	public void setPbiz(IPaginationBiz pbiz) {
		this.pbiz = pbiz;
	}

	public void setGbiz(AbstractBiz gbiz) {
		this.gbiz = (TGroupBiz) gbiz;
	}

}
